package day37.edu;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

// Created: 07/10/2025, ChangJiang Ru
public class UDPTest {
    // Sender
    @Test
    public void test1() throws Exception
    {
        // Create instance of DatagramSocket
        DatagramSocket ds = new DatagramSocket();

        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port  = 9090;
        byte[] bytes = "Do you study english and programming ?".getBytes("utf-8");
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, inetAddress, port);

        // send the data
        ds.send(packet);

        // close DatagramSocket
        ds.close();
    }

    // Receiver
    @Test
    public void test2() throws IOException {
        int port = 9090;
        DatagramSocket ds = new DatagramSocket(port);

        byte[] buffer = new byte[1024 * 64];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        // receive data
        ds.receive(packet);

        // get data, print the control
        String str = new String(packet.getData(), 0, packet.getLength());
        System.out.println(str);

        // close DatagramSocket
        ds.close();
    }
}
